package pers.yurwisher.rubick.common.security;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import pers.yurwisher.rubick.common.enums.UserClientType;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 2020年9月21日 10:50:20
 *
 * @author yq
 */
@Slf4j
public class TokenProvider implements InitializingBean {

    private final CustomSecurityProperties properties;

    public TokenProvider(CustomSecurityProperties properties) {
        this.properties = properties;
    }

    private Map<UserClientType, List<CustomSecurityProperties.ClientTokenConfig>> userTokenConfigMap;

    @Override
    public void afterPropertiesSet() throws Exception {
        if (CollectionUtil.isNotEmpty(properties.getClientTokenConfigs())) {
            //客户端token配置
            userTokenConfigMap = properties.getClientTokenConfigs().stream().collect(Collectors.groupingBy(CustomSecurityProperties.ClientTokenConfig::getType));
        }
    }

    /**
     * 创建Token
     *
     * @return token
     */
    public String generateToken() {
        return IdUtil.simpleUUID();
    }

    /**
     * 从请求中获取token
     *
     * @param request 请求
     * @return token
     */
    public String getToken(HttpServletRequest request) {
        final String requestHeader = request.getHeader(properties.getHeader());
        if (StrUtil.isNotBlank(requestHeader) && requestHeader.startsWith(properties.getType())) {
            return requestHeader.substring(properties.getType().length() + 1);
        } else {
            log.debug("非法Token：[{}]", requestHeader);
        }
        return null;
    }

    public CustomSecurityProperties.ClientTokenConfig getClientTokenConfig(UserClientType type) {
        return userTokenConfigMap.get(type).get(0);
    }

    public String getTokenType() {
        return properties.getType();
    }
}
